package com.hy.movie.service.impl;

import cn.hutool.http.HttpUtil;
import com.hy.movie.common.CommonResult;
import com.hy.movie.common.RedisKey;
import com.hy.movie.config.RedisConfig;
import com.hy.movie.model.dto.MessageLoginDto;
import com.hy.movie.service.UserService;
import com.hy.movie.util.SendMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Value("${wxmini.appid}")
    private String appid;

    @Value("${wxmini.secret}")
    private String secret;
    @Autowired
    private RedisTemplate<String, MessageLoginDto> redisTemplate;
    private final static String MESSAGE_KEY = "hy:movie:message:{phoneNumber}";
    @Autowired
    private RedisTemplate<String, String> redisTemplate1;
    @Autowired
    private SendMessage sendMessage;
    /**
     * 短信登录
     *
     * @param messageLoginDto
     * @return
     */
    public CommonResult messageLogin(MessageLoginDto messageLoginDto) {
        if (messageLoginDto == null) {
            return new CommonResult(1, "verity is null");
        }

        MessageLoginDto information = redisTemplate.opsForValue().get(MESSAGE_KEY.replace("{phoneNumber}", messageLoginDto.getPhoneNumber()));
        if(information == null){
            return new CommonResult(2, "information is null");
        }
        String verityCode = information.getVerityCode();
        if(verityCode.equals(messageLoginDto.getVerityCode())){
            return  CommonResult.SUCCESS();
        }
        return new CommonResult(2, "verity code not equal");
    }

    public CommonResult sendMessage(MessageLoginDto messageLoginDto) {

        if (messageLoginDto == null) {
            return new CommonResult(1, "verity is null");
        }
        if (messageLoginDto.getPhoneNumber() == null) {
            return new CommonResult(1, "phoneNumber is null");
        }
        String randCode = randCode();
        String sendCode = sendMessage.send(messageLoginDto.getPhoneNumber(), randCode);
        if(null == sendCode){
            return new CommonResult(1, "sendMail is null");
        }
        messageLoginDto.setVerityCode(randCode);
        redisTemplate.opsForValue().set(MESSAGE_KEY.replace("{phoneNumber}", messageLoginDto.getPhoneNumber()), messageLoginDto ,5,TimeUnit.MINUTES);
        MessageLoginDto addMessage = redisTemplate.opsForValue().get(MESSAGE_KEY.replace("{phoneNumber}", messageLoginDto.getPhoneNumber()));
        if (addMessage == null) {
            return CommonResult.FAIL("add fail");
        }
        return  CommonResult.SUCCESS();
    }

    @Override
    public CommonResult getSessionId(String code) {

        String url="https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";

        String replaceUrl=url.replace("{0}",appid).replace("{1}",secret).replace("{2}",code);
        String res = HttpUtil.get(replaceUrl);
        String uuid= UUID.randomUUID().toString();

        redisTemplate1.opsForValue().set(RedisKey.WX_SESSION_ID+uuid,res,30, TimeUnit.MINUTES);
        Map<String,String> map=new HashMap<>();
        map.put("sessionId",uuid);
        return  CommonResult.SUCCESS(map);
    }

    private String randCode(){
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            int r = random.nextInt(10); //每次随机出一个数字（0-9）
            code = code + r;  //把每次随机出的数字拼在一起
        }
        return code;
    }
}
